// https://leetcode-cn.com/problems/string-to-integer-atoi/submissions/
class Solution {
public:
    int myAtoi(string s) {
        int ind = 0, num = 0, flag = 1, pre_max = INT_MAX / 10, d = INT_MAX % 10;
        while (ind < s.size() && s[ind] == ' ') ind++; // 去除前导零
        if (s[ind] == '+') flag = 1, ++ind;
        else if (s[ind] == '-') flag = -1, ++ind;
        while (ind < s.size()) {
            if (s[ind] < '0' || s[ind] > '9') break;
            if (num > pre_max || (num == pre_max && s[ind] - '0' > d)) {
                if (flag == -1) return INT_MIN;
                return INT_MAX;
            }
            num = num * 10 + (s[ind] - '0');
            ++ind;
        }
        return num * flag;
    }
};